#include<iostream>
#include <sstream>
#include <string.h>
#include<stdlib.h>

using namespace std;
static string temp = "/tmp/.temp";
class Utility {

	public :
	static int indexOf(string strInput, string subStr) {
		int num = -1;
		size_t iIndex = strInput.find(subStr);
		if(iIndex != string::npos) {
			num = iIndex;
		}
		return num;
	}

	static bool endswith(string str, string substr) {
		int num = indexOf(str, substr);
		if (num == (str.length() - substr.length())) {
			return true;
		}
		return false;
	}

	static bool startswith(string str, string substr) {
		int num = indexOf(str, substr);
		if (num == 0) {
			return true;
		}
		return false;
	}

	static string trim(string str) {
		string::size_type pos = str.find_last_not_of(' ');
		if(pos != string::npos) {
			str.erase(pos + 1);
			pos = str.find_first_not_of(' ');
			if(pos != string::npos) {
				str.erase(0, pos);
			}
		} else {
			str.erase(str.begin(), str.end());
		}
		return str;
	}
		
	static bool checkInternal(string command, bool flag) {
		string internalCommands1[] = {"cd", "pwd", "export","fg"};
		string internalCommands2[] = {"echo", "history"};
		int n1 = sizeof(internalCommands1)/sizeof(internalCommands1[0]);
		int n2 = sizeof(internalCommands2)/sizeof(internalCommands2[0]);
		if(flag) {
			for(int i=0;i<n1;i++) {
				if(command == internalCommands1[i]) {
					return true;
				}
			}
		} else {
			for(int i=0;i<n2;i++) {
				if(command == internalCommands2[i]) {
					return true;
				}
			}
		} 
		return false;
	}
	
	static int openFile(string file, bool read, bool append) {
		int fd=-1;
		string s;
		if(file != "") 
			if(read)
				if(append){ 
					ofstream myfile;
					myfile.open(temp.c_str(),ios_base::in|ios_base::out|ios_base::trunc);
					if (myfile.is_open()) {
						Utility::sys_start();
						cout<<">";
						Utility::sys_end();
						getline(cin, s);
						while(s!=file) {
							myfile<<s;
							myfile<<endl;
							Utility::sys_start();
							cout<<">";
							Utility::sys_end();
							getline(cin, s);
						}
						myfile.close();
					} 
					fd = open(temp.c_str(), O_RDONLY);
				}
				else fd = open(file.c_str(), O_RDONLY);
		else if(append)  fd = open(file.c_str(), O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IRGRP | S_IWGRP | S_IWUSR);
		else fd = open(file.c_str(), O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IRGRP | S_IWGRP | S_IWUSR);
		if(file != "" && fd == -1) {
			Utility::err_start();
			cout<<"Error opening file :: "<<file<<endl;
			Utility::err_end();
		}
		return fd;
	}

	static void sys_start() {
		cout << "\033[1;32m";
	}

	static void sys_end() {
		cout<<"\033[0m";
	}

	static void err_start() {
		cout << "\033[1;31m";
	}

	static void err_end() {
		cout<<"\033[0m";
	}

	static void out_start() {
		cout << "\033[1;34m";
	}

	static void out_end() {
		cout<<"\033[0m";
	}
};
